package com.zgis.monitor.service.impl;

import com.zgis.monitor.config.MonitorConfig;
import com.zgis.monitor.model.ServiceStatus;
import com.zgis.monitor.model.dto.ServiceListDTO;
import com.zgis.monitor.service.MonitorService;
import com.zgis.monitor.util.SshUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * jar服务监控
 */
@Service
@Slf4j
public class JarMonitorService implements MonitorService
{
    private final List<MonitorConfig.ServerConfig> serverConfigs;

    public JarMonitorService(MonitorConfig monitorConfig)
    {
        this.serverConfigs = monitorConfig.getServers();
    }

    private Map<String, ServiceStatus> lastStatusMap;

    @Override
    public ServiceStatus checkStatus(MonitorConfig.ServerConfig server, MonitorConfig.ServiceConfig service)
    {
        ServiceStatus status = new ServiceStatus();
        status.setServerIp(server.getIp());
        status.setServiceId(service.getId());
        status.setServiceName(service.getName());
        status.setType("JAR");
        status.setLastCheckTime(LocalDateTime.now());

        try
        {
            // 检查端口是否被占用
            String command = String.format("netstat -tlnp | grep :%d | awk '{print $7}' | cut -d'/' -f1", service.getPort());
            String result = SshUtil.executeCommand(
                    server.getIp(), server.getSshPort(),
                    server.getUsername(), server.getPassword(),
                    command
            );

            if (result.contains("ERROR"))
            {
                status.setRunning(false);
                status.setMessage(result);
                return status;
            }

            if (!result.isEmpty())
            {
                status.setRunning(true);
                status.setPid(result);
                status.setMessage("服务运行中");
            }
            else
            {
                status.setRunning(false);
                status.setMessage("服务未运行");
            }
        }
        catch (Exception e)
        {
            status.setRunning(false);
            status.setMessage("检查失败: " + e.getMessage());
            log.error("检查Jar服务状态失败", e);
        }

        return status;
    }

    @Override
    public boolean startService(MonitorConfig.ServerConfig server, MonitorConfig.ServiceConfig service)
    {
        if (service.getStartCommand() == null || service.getStartCommand().isEmpty())
        {
            log.error("Jar服务启动命令未配置: {}", service.getId());
            return false;
        }

        // 使用nohup后台启动
        String command = String.format("nohup %s > /dev/null 2>&1 &", service.getStartCommand());
        String result = SshUtil.executeCommand(
                server.getIp(), server.getSshPort(),
                server.getUsername(), server.getPassword(),
                command
        );

        try
        {
            Thread.sleep(1000);
            ServiceStatus status = checkStatus(server, service);
            return status.isRunning();
        }
        catch (InterruptedException e)
        {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    @Override
    public boolean stopService(MonitorConfig.ServerConfig server, MonitorConfig.ServiceConfig service)
    {
        // 先获取进程ID
        String pidCommand = String.format("netstat -tlnp | grep :%d | awk '{print $7}' | cut -d'/' -f1", service.getPort());
        String pid = SshUtil.executeCommand(
                server.getIp(), server.getSshPort(),
                server.getUsername(), server.getPassword(),
                pidCommand
        );

        if (pid.isEmpty() || pid.contains("ERROR"))
        {
            log.info("Jar服务未运行，无需停止: {}", service.getId());
            return true;
        }

        String command = "kill " + pid;
        String result = SshUtil.executeCommand(
                server.getIp(), server.getSshPort(),
                server.getUsername(), server.getPassword(),
                command
        );

        // 检查是否停止成功
        try
        {
            Thread.sleep(500);
            ServiceStatus status = checkStatus(server, service);
            return !status.isRunning();
        }
        catch (InterruptedException e)
        {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    @Override
    public boolean restartService(MonitorConfig.ServerConfig server, MonitorConfig.ServiceConfig service)
    {
        return MonitorService.super.restartService(server, service);
    }

    @Override
    public List<ServiceStatus> getAllServiceStatus()
    {
        return null;
    }

    /**
     * 获取所有服务列表，包含基本信息和状态
     */
    public List<ServiceListDTO> getServiceListWithStatus()
    {
        return Collections.emptyList();
    }
}
    